<?php

class membership_model extends CI_Model {
	
	function validate()
	{
		$this->db->where('email', strtolower($this->input->post('email')));		
		$this->db->where('passwd', md5($this->input->post('password')));
		$this->db->where('deleted', 0);
		$this->db->from('users u');
		$this->db->join('sellers s', 'u.id = s.user_id', 'left');
		$this->db->select("u.*, s.id seller_id");
		$query = $this->db->get();	
		if($query->num_rows() > 0) {
			$row = $query->first_row();
			return $row;	
		}
		 else {
		 	return false;
		 }
	}
	
	function verify_member_info($userid,$expiredcode)  {
		
		$this->db->where('id', $userid);		
		$this->db->where('email_link_code', $expiredcode);
		$query = $this->db->get('users');	
		if($query->num_rows() > 0) {
			$row = $query->first_row();
			return $row;	
		}
		 else {
		 	return false;
		 }
	}
	
	function get_random_password() {
	
		$chars = 'abcdefghijkmnopqrstuvwxyz023456789!@#$';
		srand((double)microtime() * 1000000);
		$new_pass='';
		$chars_length = strlen($chars) - 1;
		for ($i = 0; $i < 10; $i++) {
			$new_pass .= substr($chars, (rand() % $chars_length), 1);
		}
		return $new_pass;
	}
	
	function get_random_linkcode() {
	
		$chars = 'abcdefghijkmnopqrstuvwxyz023456789';
		srand((double)microtime() * 1000000);
		$new_pass='';
		$chars_length = strlen($chars) - 1;
		for ($i = 0; $i < 10; $i++) {
			$new_pass .= substr($chars, (rand() % $chars_length), 1);
		}
		return $new_pass;
	}
	
	function get_member_info($email=false, $password=false,$id=false) {
		
		if ($email) {
			$this->db->where('email',$email) ;
		}
		if ($password) {
			$this->db->where('passwd',md5($password));
		}
		if (!empty($id)) {
			if($id > 0) $this->db->where('id',$id);
			else $this->db->where('id !=', abs($id));
		}
		$query = $this->db->get('users');
		if($query->num_rows() > 0) {
			$row = $query->first_row();
			return $row;	
		}
		 else {
		 	return false;
		 }
	}
		

	function update_member_change_password($user) {
		$update_member_data = array(
			'passwd' => $user->passwd,
			'last_login'       => NULL,
			'fail_login_times' => 0,
			'password_expired' => $user->password_expired 
		);
			
		
		$this->db->where('id', $user->id);
		$this->db->update('users',$update_member_data);
	}
	
	function update_password() {

		$id = $this->session->userdata('id') ;	
		$update_member_data = array(			
			'passwd'       => md5($this->input->post('newpassword')),	
            'password_expired' => '0',
		);
		
        $this->db->set("updated_at",'NOW()',false);
        
		$this->db->where('id', $id);
		$this->db->update('users',$update_member_data);
		
		// add log 
		$user_name = $this->session->userdata('email');
		$content = "User:<br>";
		$content .= "Email: ".$user_name."<br>";
		$content .= "Role: ".$this->session->userdata('usertype');
		modules::run('actionlog/saveActionLog',ACTION_UPDATE." password","Maintain user",$id,$content,$user_name,0);
	}
	
	function update_member_login($user) {
		$this->load->helper('date');		
		$update_member_data = array(	
			'fail_login_times' => 0,
			'active' => 1, 
		);	
		$this->db->set("last_login",'NOW()',false);	
		
		$this->db->where('id', $user->id);
		$this->db->update('users',$update_member_data);
		
		//save log
		modules::run('actionlog/saveActionLog', ACTION_UPDATE." user - Activate","Maintain user", $user->id,"users:<br> id ". $user->id . "<br>". var_export($update_member_data, true) , $user->email);
	}
	
	function sendRegisterEmail($user) {
		error_reporting(0);
		
		$this->load->library('parser');
		$url = base_url()."login/activate/".$user->id."/".$user->email_link_code;
		$enddate = $user->email_link_expires;
		$siteurl =  base_url() ;
				
		$data = array(
			'full_name_customer'=>'',
			'full_name_fundraiser'=>'',
			'message_to_charity'=>'',
			'address_fundraiser'=>'',
			'phone_fundraiser'=>'',
			'email_fundraiser'=>'',
			'website_fundraiser'=>'',
			'Organization\'s_Representative_Name'=> '',
			'Representative_Title'=>'',
			'nominortor_name'=>'',
			'Amount_giving_to_charity'=>'',
			'expireday_fundraiser'=>$this->public_model->getSystemParameterValue("expireday_fundraiser"),		
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'url' =>$url,
            'enddate' => $enddate,
            'siteurl' => $siteurl,
            'email'=>$user->email,
			'password'=>$user->passwd
        );
		
		$this->load->model('emailtemplate/emailtemplate_model');
		$template  = $this->emailtemplate_model->getEmailTeplateByName("Register Email") ;
		$emailContent = $this->parser->parse_string($template->content, $data, TRUE);		
					
		$fromEmail= $this->public_model->getSystemParameterValue('defaultEmailFromAddress');
		//$this->load->library('email');
	  	
        $config['protocol']='sendmail';
	  	$config['smtp_host']=$this->public_model->getSystemParameterValue('hostmail');
        $config['smtp_port']=$this->public_model->getSystemParameterValue('mailport');
        $config['smtp_user']=$fromEmail;
        $config['smtp_pass']=$this->public_model->getSystemParameterValue('defaultPassword');
	  	$config['mailtype'] = 'html';
        
        $this->load->library('email',$config);                
	  	//$this->email->initialize($config);
        
	  	$this->email->from($fromEmail, $this->public_model->getSystemParameterValue('websiteURL'));
	    $this->email->to($user->email); 
		
        $strSubject = $this->public_model->getSystemParameterValue('websiteURL').': Activate Account ';
	    $this->email->subject($strSubject);	    
	    $this->email->message($emailContent);

		$to = $user->email;
		$subject = $strSubject;
		$txt = $emailContent;
		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
		// More headers
		$headers .= 'From: '. $fromEmail;
		
		return mail($to,$subject,$txt,$headers);	    
	    //return $this->email->send();
	}
	
	function sendResetPasswordEmail($user) {
		$this->load->model('emailtemplate/emailtemplate_model');
		$this->load->library('parser');
		$url =base_url();
		
		$template  = $this->emailtemplate_model->getEmailTeplateByName("Reset Password") ;
		
		$data = array(
			'full_name_customer'=>'',
			'full_name_fundraiser'=>'',
			'message_to_charity'=>'',
			'address_fundraiser'=>'',
			'phone_fundraiser'=>'',
			'email_fundraiser'=>'',
			'website_fundraiser'=>'',
			'Organization\'s_Representative_Name'=> '',
			'Representative_Title'=>'',
			'nominortor_name'=>'',
			'Amount_giving_to_charity'=>'',
			'expireday_fundraiser'=>$this->public_model->getSystemParameterValue("expireday_fundraiser"),	
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email'=>$user->email,
            'password' => $user->passwd,
            'enddate' => '',
            'siteurl' => base_url(),
            'url' => $url
            );
		$emailContent = $this->parser->parse_string($template->content, $data, TRUE);		
			
		$fromEmail= $this->public_model->getSystemParameterValue('defaultEmailFromAddress');
		$smtp_host=$this->public_model->getSystemParameterValue('hostmail');
		$this->load->library('email');
	  	$config['protocol']='smtp';
	  	$config['smtp_host']=$smtp_host;
	  	$config['mailtype'] = 'html';
	  	$this->email->initialize($config);
	  	$this->email->from($fromEmail, $this->public_model->getSystemParameterValue('websiteURL'));
	    $this->email->to($user->email); 
		$strSubject=$this->public_model->getSystemParameterValue('websiteURL') . ' - Reset Password ';
	    $this->email->subject($strSubject);	    
	    $this->email->message($emailContent);
	    
	    
	    $to = $user->email;
		$subject = $strSubject;

		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
		// More headers
		$headers .= 'From: '. $fromEmail;
		
		mail($to,$subject, $emailContent, $headers);	    
	    //$this->email->send();	
	
	}
	function getCountries() {
		
		$this->db->where('active', '1');		
		$query = $this->db->get('countries');	
		if($query->num_rows() > 0) {
			 $countrylist =  $query->result();
			 $results = array();
			 
			 foreach($countrylist as $country){
			 	$results[$country->id] = $country->name;
			 }	
			 
			 return $results;
		}
		 else {
		 	return false;
		 }		 
	}
	
	function getStates() {		
			
		$query = $this->db->get('states');	
		if($query->num_rows() > 0) {
			 $statelist =  $query->result();
			 $results = array();
			 $stateinfo = array();
			 foreach($statelist as $states){
			 	$results[$states->id] = $states;
			 }	
			 
			 return $results;
		}
		 else {
		 	return false;
		 }		 
	}
	
	function getListAccountType(){
		$result=array("PERSONAL_CHECKING"=>"Checking","PERSONAL_SAVINGS"=>"Saving");
		return $result;
	}
	
	function getCreditCardData(&$data, $user_id = 0){
		$this->load->model("public_model");	
		$data['cardtypelist']=array('Visa'=>'Visa','Master Card'=>'MasterCard','Discover'=>'Discover','American Express'=>'American Express');
		$data['monthlist']=array(1=>'01',2=>'02',3=>'03',4=>'04',5=>'05',6=>'06',7=>'07',8=>'08',9=>'09',10=>'10',11=>'11',12=>'12');
		$data['currentmonth']=date('m');
		$yearlist=array();
		$curYear=date('Y');
		for($i=$curYear;$i<=$curYear+5;$i++){
			$yearlist[$i]=$i;
		}
		$data['yearlist']=$yearlist;
		$data['currentyear']=date('Y');	
		if($user_id > 0){
			$paymentInfo = $this->public_model->getPaymentInfo(array("user_id" => $user_id));
			if(!empty($paymentInfo)) $data['paymentInfo']= $paymentInfo;	
		}
	}
	
	function populdateBuyerSignupInfo($error = null) {
		
		$this->load->model('membership_model');
		$countryList = $this->membership_model->getCountries();		
		$stateList = $this->membership_model->getStates();
		
		$var['countryList'] = $countryList;
		$var['stateList'] = $stateList;
			
        $currentCountry = COUNTRY_ID_US;
		if( $this->input->post('country')) {
			$var['currentCountryCode'] = $this->input->post('country');
            $currentCountry = $this->input->post('country');	
		} else {
			$var['currentCountryCode'] = COUNTRY_ID_US;
		}		
		
		if( $this->input->post('biCountry')) {
			$var['currentBiCountryCode'] = $this->input->post('biCountry');	
            $currentCountry = $this->input->post('biCountry');
		} else {
			$var['currentBiCountryCode'] = COUNTRY_ID_US;
		}
        
        if( $this->input->post('billCountry')) {
			$var['currentBillCountryCode'] = $this->input->post('billCountry');	
            $currentCountry = $this->input->post('billCountry');
		} else {
			$var['currentBillCountryCode'] = COUNTRY_ID_US;
		}
        
      	$var['baseUrl'] = base_url();
		
		$usStateList = array();
		 
		foreach($stateList as $states) {			
			if($states->country_id == $currentCountry) {
				$usStateList[$states->id] = $states->name;
			}
		}
				
		$var['usStateList'] = $usStateList;
		$var['sponsorList'] = $this->public_model->getSelectboxArray($this->getSponsors(), 'id', 'name');
		
		if(!empty($error)) {
			$var['error'] =  $error;		
		}
        return $var ;
	}
	
	function getSponsors($sponsor_id = null){
		$this->db->select('*');
		$this->db->where('status', 1);
		if($sponsor_id != null) $this->db->where('id', $sponsor_id);
		$query = $this->db->get('sponsors');
		$rs = null;
		if($query->num_rows > 0){
			 $rs = $query->result();
		}
		return $rs;
	}
	
	function createPlayer(){
		$rs = new stdClass();
		$rs->success = false;
		$rs->commonResponse = new stdClass();
		$rs->commonResponse->errorDescription = null;
				
		$date =  date("Y-m-d") ;
		$newdate = strtotime ( '+'. EXPIRE_ACTIVATE_DATE .' day' , strtotime ( $date ) ) ;
		$newdate = date ( 'Y-m-d' , $newdate );
		
		$new_member_insert_data = array(
			'email' => strtolower($this->input->post('email')),
			'passwd' => md5($this->input->post('password')),
			'first_name' => $this->input->post('firstname'),
			'active' => 0,
			'last_name' => $this->input->post('lastname'),
			'usertype' => USER_TYPE_USER,
			'email_link_code' => $this->get_random_linkcode(),
			'email_link_expires' => $newdate									
		);	
		
		$insert = $this->db->insert('users', $new_member_insert_data);				
		$user_id = $this->db->insert_id();
		$new_member_insert_data = (object) $new_member_insert_data;
		$new_member_insert_data->id = $user_id;
		$this->sendRegisterEmail((object)$new_member_insert_data);
        $rs->success = true;	
		$rs->user = $new_member_insert_data;
		
		return $rs;
	}
	
	function createPaymentAccount($userid, $billid, $creditCardInfo){
		$this->load->library('payment');		
		$rs = new stdClass();
		$rs->success = false;
		
		$rs = $this->payment->submitCreatePaymentAccount($creditCardInfo);
		if($rs->success = true){
			$data = array("user_id" => $userid, "address_id" => $billid, "payment_account_id" => $rs->clientRequestNumber);
			$this->insertData('paymentaccounts', $data);
		}
		return $rs;
	}
	
	function _insertPaymentTransactions($creditCardInfo=array(), $paymentInfo = array(), $orderid=0,$order_import_id=0,$amount=0,$deatailorderid=0,$action='authorize',$refundedAmount=0){
 		$insert_data = array(
			'credit_card_type' => $creditCardInfo["cardType"],		 
			'cc_last4digits' =>  $creditCardInfo["cc_last4digits"],
			'name_on_creditcard' => $creditCardInfo["cardHolderFullName"],
			'payment_engine_id' => $paymentInfo['payment_engine_id'],
			'payment_token' => $paymentInfo['payment_token'],
			'amount' => $amount,
			'exp_year' => $creditCardInfo["exp_year"],
			'exp_month' => $creditCardInfo["exp_month"],
			'action'=>$action
			);
 		$insert = $this->db->insert('paymenttransactions', $insert_data);
 		$id = null;
 		if($insert) $id = $this->db->insert_id();
 		return $id;
 	}
 	
 	function _updatePaymentTransactions($creditCardInfo=array(), $paymentInfo = array(), $orderid=0,$order_import_id=0,$amount=0,$deatailorderid=0){
 		$update_data = array(
			'order_id'  => $orderid, 
			'order_import_id'  => $order_import_id, 
			'credit_card_type' => $creditCardInfo["cardType"],		 
			'cc_last4digits' =>  $creditCardInfo["cc_last4digits"],
			'name_on_creditcard' => $creditCardInfo["cardHolderFullName"],
			'payment_engine_id' => $paymentInfo['payment_engine_id'],
			'payment_token' => $paymentInfo['payment_token'],
			'amount' => $amount,
			'detail_order_id'=>$deatailorderid,
			'exp_year' => $creditCardInfo["exp_year"],
			'exp_month' => $creditCardInfo["exp_month"]
			);
		$this->db->where('id', $paymentInfo['id']);
 		$this->db->update('paymenttransactions', $update_data);
 	}
 	
	function _getPaymentInfo($options){
		if(!empty($options['user_id'])){
			$this->db->where('pa.user_id', $options['user_id']);
			$this->db->join('paymentaccounts pa', 'pt.id = pa.payment_account_id', 'left');	
		}
		if(!empty($options['payment_account_id'])){
			$this->db->where('pt.id', $options['payment_account_id']);	
		}
		if(!empty($options['order_id'])){
			$this->db->where('pt.order_id', $options['order_id']);	
		}
		$this->db->select("pt.*");
		$query = $this->db->get('paymenttransactions pt');	
		if($query->num_rows() > 0) {
			return $query->result();	
		}
		return array();
	}
	 	
 	function getUsers($options = array()){
 		$this->db->select('*');
 		if(!empty($options['email'])) $this->db->where('email', $options['email']);
 		if(!empty($options['nickname'])) $this->db->where('nickname', $options['nickname']);
 		
		$query = $this->db->get('users');
		if($query->num_rows > 0){
			return $query->result();
		}
		return false;
 	}
}